package main

import (
	"cps/lib"
	_ "cps/routers"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/config"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"

	_ "github.com/astaxie/beego/session/mysql"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	lib.InitLogger()

	logs.Info("cps start...")
	initApp()
	beego.Run()
}

func exit(result int) {

	logs.Info("cps exit...")

	os.Exit(result)
}

func initApp() {

	// Signal
	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
	go func() {
		<-signalChan
		exit(0)
	}()

	// init DB
	dbURL, err := getDBUrl()
	if err != nil {
		beego.Error("Error on parse database config, %s", err.Error())
		os.Exit(1)
	}
	orm.RegisterDataBase("default", "mysql",
		dbURL,
		5,
		5)
	orm.Debug = true

}

func getDBUrl() (string, error) {
	mysqlConfigPath := filepath.Join(beego.AppPath, "conf", "mysql.ini")
	mysqlConfig, err := config.NewConfig("ini", mysqlConfigPath)
	if err != nil {
		beego.Error("new mysql config error", err.Error())
		return "", err
	}

	envRunMode := os.Getenv("CPS_RUNMODE")
	if envRunMode == "" {
		envRunMode = beego.DEV
	}

	username := mysqlConfig.String(envRunMode + "::username")
	password := mysqlConfig.String(envRunMode + "::password")
	protocol := mysqlConfig.String(envRunMode + "::protocol")
	ip := mysqlConfig.String(envRunMode + "::ip")
	port := mysqlConfig.String(envRunMode + "::port")
	dbname := mysqlConfig.String(envRunMode + "::dbname")
	charset := mysqlConfig.String(envRunMode + "::charset")

	dbURL := username + ":" + password + "@" + protocol + "(" + ip + ":" + port + ")" + "/" + dbname + "?charset=" + charset

	return dbURL, nil
}
